
package pe.pucp.netbeans.common.util;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.swing.JOptionPane;
import org.openide.util.Exceptions;

/**
 *
 * @author Diego
 */
public class WriterThread extends Thread {
    private OutputStream os;
    private BufferedWriter bw;
    private boolean iniciado;
    private boolean finalizado;
    public WriterThread(OutputStream os) {
        this.os = os;
    }

    public synchronized void nuevaSalida(String s) {
        if (! iniciado) return;
        try {
            JOptionPane.showMessageDialog(null, "va escribir: "+s);
            bw.write(s);
            JOptionPane.showMessageDialog(null, "ya escribio");
            bw.flush();
            JOptionPane.showMessageDialog(null, "ya hizo flush");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null,"error al escribir, va llamar a finalizar");
            finalizar();
        }
    }

    public synchronized void  finalizar() {
        if (finalizado) return;
        finalizado = true;
        notify();
    }

    @Override
    public synchronized void run() {
        iniciado = true;
        OutputStreamWriter osw = null;
            osw = new OutputStreamWriter(os);
            bw = new BufferedWriter(osw);
        try {
            wait();
        } catch (InterruptedException ex) {
            Exceptions.printStackTrace(ex);
        }
        try {
            bw.close();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        try {
            osw.close();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        try {
            os.close();
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
